package com.mornd.gulimall.ware.config.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: mornd
 * @dateTime: 2023/8/26 - 7:16
 * 声明队列，交换机，绑定关系
 */
@Slf4j
@Configuration
public class StockMQConfig {

    /**
     * 声明库存解锁交换机
     * @return
     */
    @Bean
    public Exchange stockEventExchange() {
        return ExchangeBuilder.topicExchange("stock-event-exchange")
                .durable(true)
                .build();
    }

    /**
     * 普通队列
     * @return
     */
    @Bean
    public Queue stockReleaseQueue() {
        return new Queue("stock.release.queue",
                true, false, false);
    }

    /**
     * 死信队列 内部使用，不允许消费者监听
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        return QueueBuilder.durable("stock.delay.queue")
                // 绑定死信交换机
                .deadLetterExchange("stock-event-exchange")
                // 路由键
                .deadLetterRoutingKey("stock.release")
                // 50分钟
                .ttl((int) TimeUnit.MINUTES.toMillis(50))
                .build();
    }

    @Bean
    public Binding stockReleaseBinding() {
        return BindingBuilder.bind(stockReleaseQueue())
                .to(stockEventExchange())
                .with("stock.release.#")
                .noargs();
    }

    @Bean
    public Binding stockLockedBinding() {
        return BindingBuilder.bind(stockDelayQueue())
                .to(stockEventExchange())
                .with("stock.locked")
                .noargs();
    }

//    @RabbitListener(queues = "stock.release.queue")
//    public void listener(Message msg, Map map, Channel channel) throws IOException {
//        log.debug("收到消息：{}", map);
//        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
//        channel.basicAck(deliveryTag, false);
//    }

}
